<template>
  <div class="map-box">
    <div
      id="mainMap"
      style="width: 100%;height:5rem;background: none;"/>
    <div v-show="isReturn" class="query-return">
      <ul>
        <li :class="{'active_color': true}" @click="returnSuper">
          <p>&nbsp;</p>
          <p>返回</p>
        </li>
      </ul>
    </div>
  </div>
</template>
<script >
import Provinces from './provinceAll.js'
import ChinaCode from './chinaCode.js'
import CityMap from './cityMap.js'
import qs from 'qs'
export default {
  props: {
    isShowTag: {
      type: Boolean,
      default: true
    }
  },
  data () {
    return {
      cityName: '',
      isReturn: false,
      clickIndex: 1,
      modelType: '1',
      charts: null,
      areaName: '',
      tabMapName: [],
      colorInit: ['#1E9EE4', '#4CACE1', '#74BAE1', '#9BC9E3', '#D0E1E9'],
      mapData: {},
      countryData: {}
    }
  },
  mounted () {
    this.$nextTick(() => {
      this.init()
    })
  },
  methods: {
    // 销毁当前存在的地图
    disposed () {
      if (this.charts) {
        this.charts.dispose()
      }
    },
    // 注册和渲染地图
    createMap (map, chinaMap, data) {
      var that = this
      // 地图容器
      var echarts = that.$echarts

      var chart = (this.charts = echarts.init(
        document.getElementById('mainMap')
      ))
      var colorValue = []
      for (var i = 0; i < data.length; i++) {
        colorValue.push(data[i].value)
      }

      var colorValueMax = Math.max.apply(null, colorValue)

      var option = {
        backgroundColor: '',
        title: {
          text: '',
          subtext: '',
          link: '',
          left: 'center',
          textStyle: {
            color: '#4fd4f7',
            fontSize: 12,
            fontWeight: 'normal',
            fontFamily: 'Microsoft YaHei'
          },
          subtextStyle: {
            color: '#fff',
            fontSize: 12,
            fontWeight: 'normal',
            fontFamily: 'Microsoft YaHei'
          }
        },
        tooltip: {
          show: true,
          formatter: function (params) {
            if (params.data && params.data.value === 0) {
              return '此区域值为0'
            } else if (!params.data) {
              return params.name + '此城市未开通'
            }
          },
          textStyle: {
            color: '#4fd4f7'
          }
        },
        toolbox: {
          show: false,
          orient: 'vertical',
          left: 'right',
          top: 'center',
          feature: {
            dataView: { readOnly: false },
            restore: {},
            saveAsImage: {}
          },
          iconStyle: {
            normal: {
              color: '#fff'
            }
          }
        },
        dataRange: {
          show: false,
          min: 0,
          max: colorValueMax,
          color: this.colorInit
        },
        animationDuration: 1000,
        animationEasing: 'cubicOut',
        animationDurationUpdate: 1000
      }

      // let mapType = '中国'
      // if (map === '中国' || map === 'china' || map === '全国战区' || map === '中部战区' || map === '东部战区' || map === '南部战区' || map === '西部战区' || map === '北部战区') {
      //   mapType = '中国'
      // } else {
      //   mapType = map
      // }
      option.title.subtext = map
      function renderMap (map, data) {
        option.series = [
          {
            name: map,
            type: 'map',
            mapType: map,
            roam: true,
            scaleLimit: { min: 0.8, max: 1.9 }, // 缩放
            center: '',
            nameMap: {
              china: ''
            },
            label: {
              normal: {
                show: false,
                formatter: function (params) {
                  if (params.data && params.data.value >= 0) {
                    return params.name
                  } else {
                    return ''
                  }
                }
              },
              emphasis: {
                show: true,
                formatter: function (params) {
                  if (params.data && params.data.value >= 0) {
                    return params.name
                  } else {
                    return ''
                  }
                }
              }
            },
            itemStyle: {
              normal: {
                areaColor: '#333E58',
                borderColor: '#08183F',
                textStyle: {
                  color: '#ddd'
                }
              },
              emphasis: {
                areaColor: '#333E58',
                label: {
                  show: true,
                  textStyle: {
                    color: '#ed7d31'
                  }
                }
              }
            },
            data: data
          }
        ]
        // 渲染地图
        chart.setOption(option)
      }
      // 地图点击事件
      let len = that.tabMapName.length
      if (len > 1) {
        that.isReturn = true
      } else {
        that.isReturn = false
      }
      chart.on('click', function (params) {
        params.event.event.stopPropagation()
        if (!params.data || !params.data.region || !params.data.value || params.data.value === 0) {
          return
        }
        that.code = params.data.region
        that.areaName = params.data.pName
        that.isReturn = true
        that.clickIndex++
        that.tabMapName.push({
          name: that.areaName,
          code: that.code,
          isLeaf: params.data.isLeaf
        })
        that.mapDataQuery(that.areaName, that.code, that.modelType)
        // if (params.data.name !== '') {
        // } else {
        //   that.tabMapName.push({
        //     name: params.data.name,
        //     code: that.code,
        //     isLeaf: params.data.isLeaf
        //   })
        //   that.mapDataQuery(params.data.name, that.code, that.modelType)
        // }
      })
      // 注册地图
      echarts.registerMap(map, chinaMap)
      renderMap(map, data)
    },
    // 返回上级
    returnSuper () {
      this.clickIndex = this.tabMapName.length
      this.clickIndex--
      let code = ''
      let map = ''
      let count
      if (this.clickIndex - 1 === 0) {
        this.isReturn = false
        code = this.tabMapName[0].code
        map = this.tabMapName[0].namename
        this.tabMapName.splice(1, this.tabMapName.length)
      } else {
        code = this.tabMapName[this.clickIndex - 1].code
        map = this.tabMapName[this.clickIndex - 1].name
        count = this.tabMapName.length - this.clickIndex
        this.tabMapName.splice(this.clickIndex, count)
      }
      this.mapDataQuery(map, code, this.modelType, this.tabMapName)
    },

    // 渲染全中国地图
    getChina (map, data) {
      var that = this
      var d = []
      if (data) {
        d = data
      }
      this.$api.post('/map/getResources', qs.stringify({
        path: 'china/china.json'
      })).then(function (res) {
        if (res.status === 200) {
          that.mapData = res.data.map
          that.disposed()
          that.createMap(map, that.mapData, d)
        }
      })
    },
    // 渲染中国某个省份地图
    getProvince (map, pName, data) {
      var that = this
      var provincesMap = Provinces.provinces
      var d = []
      if (data) {
        d = data
      }
      let provincesJson = provincesMap[map]
      if (pName) {
        provincesJson = provincesMap[pName]
      }
      this.$api.post('/map/getResources', qs.stringify({
        path: 'province/' + provincesJson + '.json'
      })).then(function (res) {
        if (res.status === 200) {
          that.mapData = res.data.map
          that.disposed()
          that.createMap(map, that.mapData, d)
        }
      })
    },
    // 渲染中国某个城市地图
    getCity (map, pName, data) {
      var that = this
      var cityMap = CityMap.cityMap
      var d = []
      if (data) {
        d = data
      }
      let cityJson = cityMap[map]
      if (pName) {
        cityJson = cityMap[pName]
      }
      this.$api.post('/map/getResources', qs.stringify({
        path: 'city/' + cityJson + '.json'
      })).then(function (res) {
        if (res.status === 200) {
          that.mapData = res.data.map
          that.disposed()
          that.createMap(map, that.mapData, d)
        }
      })
    },
    getCountry (map, pName, data) {
      let that = this
      let cityMap = CityMap.cityMap
      let d = []
      let childMap = {
        'type': 'FeatureCollection',
        'features': []
      }
      if (data) {
        d = data
      }
      if (pName) {
        this.$api.post('/map/getResources', qs.stringify({
          path: 'city/' + cityMap[pName] + '.json'
        })).then(function (res) {
          if (res.status === 200) {
            let features = res.data.map.features
            for (let i = 0; i < features.length; i++) {
              if (features[i].properties.name === map) {
                childMap.features.push(features[i])
              }
            }
            that.disposed()
            that.createMap(map, childMap, d)
          }
        })
      } else {
        let features = that.mapData.features
        for (let i = 0; i < features.length; i++) {
          if (features[i].properties.name === map) {
            childMap.features.push(features[i])
          }
        }
        that.disposed()
        that.createMap(map, childMap, d)
      }
    },
    // 外部调用地图渲染方法
    getData (mapObj, flag) {
      let that = this
      let map = mapObj.mapName
      let pName = mapObj.pName
      let data = mapObj.data
      this.modelType = mapObj.type || '1'
      this.tabMapName = mapObj.tabName || []
      this.clickIndex = this.tabMapName.length
      this.$nextTick(() => {
        if (map in Provinces.provinces) {
          // 如果点击的是34个省、市、自治区，绘制选中地区的二级地图
          that.getProvince(map, null, data)
        } else if (map in CityMap.cityMap) {
          // 显示县级地图
          that.getCity(map, null, data)
        } else if (map in that.countryData) {
          that.getCountry(map, that.countryData[map], data)
        } else {
          if (pName in Provinces.provinces) {
            that.getProvince(map, pName, data)
          } else if (pName in CityMap.cityMap) {
            that.getCity(map, pName, data)
          } else {
            that.getChina(map, data)
          }
        }
      })
    },
    // 地图数据处理
    setMap (data) {
      let d = []
      let areaRegion = data.areaRegion || []
      for (let i = 0; i < areaRegion.length; i++) {
        let areaType = areaRegion[i].type
        let region = areaRegion[i].code
        let pName = areaRegion[i].name
        let children = areaRegion[i].biRegionIds
        if (areaType === 1) {
          for (let j = 0; j < children.length; j++) {
            d.push({
              name: children[j].name,
              value: areaRegion[i].value,
              region: region,
              pName: pName
            })
          }
        } else {
          d.push({
            name: areaRegion[i].name,
            value: areaRegion[i].value,
            region: region,
            pName: pName
          })
        }
      }
      return d
    },
    // 返回外部组件参数
    mapDataQuery (map, code, type) {
      if (type) {
        this.modelType = type
      }
      this.$emit('mapDataQuery', this.modelType, map, code, this.tabMapName)
    },
    // 初始化地图组件是否市全国全部数据
    init () {
      let that = this
      let chinaCode = ChinaCode.region
      let newName = ''
      for (let i = 0; i < chinaCode.length; i++) {
        if (chinaCode[i].type === 2) {
          newName = chinaCode[i].region_name
        } else if (chinaCode[i].type === 3) {
          that.countryData[chinaCode[i].region_name] = newName
        }
      }
    }
  }
}
</script>
<style lang='scss'>
.map-box {
  position: relative;
  .query-return {
    width: 16%;
    position: absolute;
    right: 4%;
    top: 5%;
    ul {
      display: flex;
      display: -flex;
      li {
        display: flex;
        display: -flex;
        flex: 1;
        p {
          line-height: 0.6rem;
        }
        p:nth-child(1) {
          width: 0.25rem;
          height: 0.2rem;
          margin-top: 0.17rem;
          margin-right: 0.1rem;
          background: rgba(174, 174, 174, 0.5);
        }
        p:nth-child(2) {
          flex: 1;
        }
        &.active_color {
          p:nth-child(1) {
            background: #ed7d31;
          }
        }
      }
    }
  }

}
</style>
